package com.media.selector.media.model

import android.content.ContextWrapper
import android.database.Cursor
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import androidx.loader.app.LoaderManager
import androidx.loader.content.Loader
import com.media.selector.media.model.loader.AlbumLoader

/**
 * date        ：2020/5/11
 * author      ：蒙景博
 * description ：
 */
class AlbumCollection constructor(activity: FragmentActivity): ContextWrapper(activity), LoaderManager.LoaderCallbacks<Cursor> {

    companion object {
        private const val LOADER_ID = 1
        private const val STATE_CURRENT_SELECTION = "state_current_selection"
    }

    private var mCallbacks: AlbumCallbacks? = null
    private var mLoaderManager: LoaderManager? = null
    private var mCurrentSelection = 0
    private var mLoadFinished = false

    init {
        mLoaderManager = LoaderManager.getInstance(activity)
        mLoaderManager?.initLoader(LOADER_ID, null, this)
    }

    fun onCreate(savedInstanceState: Bundle?, callbacks: AlbumCallbacks) {
        this.mCallbacks = callbacks
        savedInstanceState?.let {
            mCurrentSelection = it.getInt(STATE_CURRENT_SELECTION)
        }
    }

    fun onSaveInstanceState(outState: Bundle) {
        outState.putInt(STATE_CURRENT_SELECTION, mCurrentSelection)
    }

    fun onDestroy() {
        mLoaderManager?.destroyLoader(LOADER_ID)
        mCallbacks = null
    }

    fun getCurrentSelection(): Int = mCurrentSelection

    fun setStateCurrentSelection(currentSelection: Int) {
        mCurrentSelection = currentSelection
    }

    override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> {
        mLoadFinished = false
        return AlbumLoader.with(this)
    }

    override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor?) {
        if (!mLoadFinished) {
            mLoadFinished = true
            mCallbacks?.onAlbumLoad(data)
        }
    }

    override fun onLoaderReset(loader: Loader<Cursor>) {
        mCallbacks?.onAlbumReset()
    }

    interface AlbumCallbacks {
        fun onAlbumLoad(cursor: Cursor?)
        fun onAlbumReset()
    }
}